<template>
  <zm-form :model="innerItem" ref="form" :rules="formRules" label-width="150px">
    <!-- 选择影院组件 -->
    <cinema-radio
      ref="CinemaRadio"
      v-model="innerItem"
      @input="(val) => handleFinalAfter(val, index)"
    ></cinema-radio>
    <!-- 执行影片 -->
    <zm-form-item
      label="执行影片"
      prop="filmType"
      :rules="{
        required: true,
        message: '请选择执行影片类型',
        trigger: 'change',
      }"
    >
      <el-radio-group v-model="innerItem.filmType">
        <el-radio label="1">全部影片</el-radio>
        <el-radio label="2">指定影片</el-radio>
      </el-radio-group>
      <!-- 指定影片 -->
      <film-selector
        v-if="innerItem.filmType === '2'"
        v-model="innerItem.filmCode"
        class="dib"
      ></film-selector>
    </zm-form-item>
    <!-- 执行制式 TEST-->
    <zm-form-item
      v-if="innerItem.copyTypeList.length > 0"
      label="执行制式"
      prop="copyType"
      :rules="{
        required: true,
        message: '请选择执行制式',
        trigger: 'change',
      }"
    >
      <zm-checkbox
        name-key="value"
        v-model="innerItem.copyType"
        :list="innerItem.copyTypeList"
        :option="{ isAllShow: true }"
      />
    </zm-form-item>
    <!-- 执行影厅 -->
    <zm-form-item
      v-if="innerItem.hallTypeList.length > 0"
      label="执行影厅"
      prop="hallType"
      :rules="{
        required: true,
        message: '请选择执行影厅',
        trigger: 'change',
      }"
    >
      <zm-checkbox
        name-key="value"
        v-model="innerItem.hallType"
        :list="innerItem.hallTypeList"
        :option="{ isAllShow: true }"
      />
    </zm-form-item>
    <!-- 可兑换票价范围 线下不展示 strat-->
    <template v-if="!isSaleCoupon&&!isOffline">
      <zm-form-item
        label="可兑换票价范围"
        class="dib"
        prop="minPrice"
        :rules="{
          validator: (rule, val, callBack) =>
            handleLimitMin(rule, val, callBack, innerItem.maxPrice),
          required: true,
          trigger: 'change',
        }"
      >
        <span>大于等于</span>
        <el-input v-model="innerItem.minPrice" clearable class="w150">
          <template slot="append">元</template>
        </el-input>
      </zm-form-item>
      <span>小于等于</span>
      <zm-form-item
        label-width="0px"
        class="vt"
        prop="maxPrice"
        :rules="{
          validator: (rule, val, callBack) =>
            handleLimitMax(rule, val, callBack, innerItem.minPrice),
          trigger: 'change',
        }"
      >
        <el-input v-model="innerItem.maxPrice" clearable class="w150">
          <template slot="append">元</template>
        </el-input>
      </zm-form-item>
    </template>
    <!-- 可兑换票价范围 end-->
    <!-- 补差规则 start -->
    <zm-form-item
      v-if="!isSaleCoupon"
      label="补差规则"
      prop="ruleType"
      :rules="{
        required: true,
        message: '请选择补差规则',
        trigger: 'change',
      }"
    >
      <zm-data-select
        v-model="innerItem.ruleType"
        :list="ruleTypeList"
        class="w200"
        clearable
        placeholder="请选择补差规则"
        @change="(val) => handleSetRuleType(val, item, index)"
      >
      </zm-data-select>
      <!-- 差额补差 start-->
      <div v-if="+innerItem.ruleType === 2" class="mt15">
        <el-radio-group v-model="innerItem.diffPriceType" @change="handleClearValue">
          <el-radio label="1" class="mb10">超过券面值时补差</el-radio>
          <el-radio label="2" class="mb10">超过固定价格时补差</el-radio>
          <el-radio label="3" class="mb10">影院结算价 - 券面值+ X 元</el-radio>
          <el-radio label="5" class="mb10">票价 - 券面值+ X 元</el-radio>
        </el-radio-group>
        <zm-form-item
          v-if="+innerItem.diffPriceType === 2"
          label="固定价格"
          class="mt10"
          prop="fixedPrice"
          :rules="{
            validator: VALID_RULES.stringNumber,
          }"
        >
          <zm-input
            class="w200"
            v-model="innerItem.fixedPrice"
            type="number"
            placeholder="请输入固定价格"
          ></zm-input>
        </zm-form-item>
        <zm-form-item
          v-if="+innerItem.diffPriceType === 3 || +innerItem.diffPriceType === 5"
          label="加价价格"
          class="mt10"
          prop="increasePrice"
          :rules="{
            validator: VALID_RULES.stringNumber,
          }"
        >
          <zm-input
            class="w200"
            v-model="innerItem.increasePrice"
            type="number"
            placeholder="请输入加价价格"
          ></zm-input>
        </zm-form-item>
      </div>
      <!-- 差额补差 end-->

      <!-- 折扣补差 start -->
      <zm-form-item label="补贴金额：" v-if="+innerItem.ruleType === 4" label-width="80px" class="mt15">
        <zm-form-item label="票价*" label-width="60px" prop="discountRule.discount" :rules="{required:true,validator: VALID_RULES.integerLimit}" class="dib">
          <zm-input class="w150" v-model="discountRule.discount" placeholder="请输入1~100">
            <template slot="append">%</template>
          </zm-input>
        </zm-form-item>

        <zm-form-item label="金额规则" label-width="80px" prop="discountRule.floatRule" :rules="{required:true,message:'请设置规则'}" class="dib">
          <zm-data-select
            v-model="discountRule.floatRule"
            :list="PRICE_RULE_LIMIT"
            class="w120"
            clearable
            placeholder="小数点位数"
          >
          </zm-data-select>
        </zm-form-item>

        <zm-form-item label="且" label-width="40px" prop="discountRule.priceRoundingType" :rules="{required:true,message:'请设置规则'}" class="dib">
          <zm-data-select
            v-model="discountRule.priceRoundingType"
            :list="PRICE_RULE_SPLICE"
            class="w120"
            clearable
          >
          </zm-data-select>
        </zm-form-item>

        <zm-form-item label="限制补贴金额上限为" prop="discountRule.subsidyTop" :rules="{required:true,validator: subsidyTopValidator}" class="dib">
          <zm-input v-model="discountRule.subsidyTop" placeholder="请输入金额" class="w150">
            <template slot="append">元</template>
          </zm-input>
        </zm-form-item>
        <tip content="该配置适用于折扣券场景<br />* 票价是指实际兑换券抵扣后的票价，公式<br />为：电影票售价*x%<br />*  补贴金额即电影票售价-票价；<br />*  补贴金额会收到补贴金额上限影响，如果<br />通过公式（电影票售价-票价）得出的补贴金<br />额高于上限，则只会把上限当作本次支付的<br />补贴金额，超出的部分会算在票价里；<br />* 配置补贴金额上限时：数据数字位数必须<br />与票价配置的小数保留规则一致；<br />（注：x为配置的折扣）" placement="top-start"></tip>
      </zm-form-item>
      <!-- 折扣补差 end -->
    </zm-form-item>
    <!-- 补差规则 end -->

    <!-- 固定补差表格 -->
    <zm-form-item>
      <zm-button
        v-if="+innerItem.ruleType === 3"
        icon="el-icon-plus"
        @click="handleSetAll"
      >
        批量设置
      </zm-button>
    </zm-form-item>
    <set-price-table-items
      :keys="setPriceKeys"
      :more="true"
      :data="innerItem"
      :all-x-axis="innerItem.hallTypeList"
      :all-y-axis="innerItem.copyTypeList"
      :x-axis="innerItem.hallType"
      :y-axis="innerItem.copyType"
      v-if="isShowSetPriceTable"
    ></set-price-table-items>

    <!-- 批量设置固定补差价格 -->
    <set-all
      v-model="showSetAll"
      v-if="showSetAll"
      @handle-after="setAllCallBack"
    ></set-all>
  </zm-form>
</template>

<script>
import ZmCollapseForm from '@/components/ZmCollapseForm'
import CinemaRadio from '@/views/product/components/CinemaRadio'
import SetPriceTableItems from '@/components/SetPriceTableItems'
import cloudApis from '@/api/src/cloud'
import FilmSelector from '@/views/product/components/FilmSelector'
import SetAll from '../SetAll'
import VALID_RULES from '@/utils/validateRule'
import Tip from '@/components/Tip'
import {PRICE_RULE_LIMIT, PRICE_RULE_SPLICE} from '@/model/type'
export default {
  name: 'RuleItem',
  components: {
    CinemaRadio,
    SetPriceTableItems,
    FilmSelector,
    SetAll,
    Tip
  },
  mixins: [],
  props: {
    // rule的元素
    item: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // rule的index
    index: {
      type: Number,
      default: 0
    },
    // 产品类型
    type: {
      type: String,
      default: ''
    },
    // 是否为线下
    isOffline: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      PRICE_RULE_LIMIT,
      PRICE_RULE_SPLICE,
      isShowSetPriceTable: false,
      showSetAll: false,
      currentItem: {},

      formRules: {},
      VALID_RULES,
      setPriceKeys: [
        { label: '', value: 'rule', placeholder: '请填写补差金额' }
      ]
    }
  },
  computed: {
    innerItem: {
      get () {
        return this.item
      },
      set (val) {
        // this.$emit('change', val)
        console.log(val)
      }
    },
    // 是否类型为优惠券
    isSaleCoupon () {
      return +this.type === 5
    },
    // 是否类型为兑换券
    isVoucher () {
      return +this.type === 1
    },
    ruleTypeList () {
      const originList = [
        {
          name: '不设置补差',
          value: '1'
        },
        {
          name: '差额补差',
          value: '2'
        },
        {
          name: '固定补差',
          value: '3'
        }
      ]
      if (this.isOffline) { // 线下除去 差额补差类型
        return originList.filter(i => i.value !== '2')
      } else {
        if (this.isVoucher) { // 兑换券+线上规则 新增类型：折扣补差
          originList.push({
            name: '折扣补差',
            value: '4'
          })
        }
        return originList
      }
    },
    discountRule () { // 折扣补差信息
      return this.innerItem.discountRule || {}
    },
    subsidyTopValidator () {
      let reg
      const regObj = {
        '0': new RegExp('^([0-9]\\d*)$'),
        '1': new RegExp('^(([0-9]\\d*))(\\.[0-9])$'),
        '2': new RegExp('^(([0-9]\\d*))(\\.(\\d){2})$')
      }
      return (rule, value, callback) => {
        const reg = regObj[this.discountRule.floatRule]
        if (!value) {
          callback(new Error('请输入正确的金额!'))
        } else if (reg.test(value) === false) {
          callback(new Error('请输入符合金额规则的值!'))
        } else if (+value > 100 || +value <= 0) {
          callback(new Error('请输入1~100的值!'))
        } else {
          callback()
        }
      }
    }
  },
  watch: {
    innerItem: {
      handler (val) {
        this.$emit('change', val)
      },
      deep: true
    }
  },
  created () {},
  methods: {
    async handleFinalAfter (val, index = 0) {
      console.log('选择影院组件回调！！！', val)
      this.$set(this.innerItem, 'relationType', val.relationType)
      this.$set(this.innerItem, 'relationId', val.relationId)
      this.isShowSetPriceTable = false
      this.innerItem.hallTypeList = []
      this.innerItem.copyTypeList = []
      // 处理执行制式、执行影厅的请求数据
      let params = {}
      let relationType = val.relationType || '-1'
      let relationId = val.relationId || '-1'
      if (relationType === '-1') {
        params = {
          type: '2',
          id: '-1'
        }
        // 选择全部影院，relationId 为 -1
        this.innerItem.relationId = '-1'
      } else {
        if (relationId !== '-1' && relationId) {
          params = {
            type: relationType,
            id: relationId
          }
        } else {
          this.innerItem.hallTypeList = []
          this.innerItem.copyTypeList = []
          return
        }
      }
      await this.getCopyTypeList(params)
      await this.getHallTypeList(params)
      if (+this.innerItem.ruleType === 3) {
        this.isShowSetPriceTable = true
      }
    },
    // 获取制式数据
    async getCopyTypeList (params) {
      const _res = await cloudApis.getCopyTypeList(params)
      console.log(_res)
      const arr = _res.map((i) => {
        return {
          id: i.id,
          value: i.name
        }
      })
      this.$set(this.innerItem, 'copyTypeList', arr)
    },
    // 获取影厅数据
    async getHallTypeList (params) {
      const _res = await cloudApis.getHallTypeList(params)
      const arr = _res.map((i) => {
        return {
          id: i.id,
          value: i.name
        }
      })
      this.$set(this.innerItem, 'hallTypeList', arr)
    },
    handleSetAll () {
      this.showSetAll = true
    },
    // 批量设置固定补差表格
    setAllCallBack (val) {
      const hallTypeSelected = this.innerItem.hallType.split(',') // 执行影厅已选的
      const copyTypeSelected = this.innerItem.copyType.split(',') // 执行制式已选的

      const res = this.innerItem.rule.map((item, _index) => {
        if (copyTypeSelected.includes(item.copyType)) {
          item.price.forEach((i) => {
            if (hallTypeSelected.includes(i.hallType)) {
              i.money = val
            }
          })
        }
        return item
      })

      this.innerItem.rule = res
    },
    handleLimitMax (rule, val, callBack, minVal) {
      const reg = new RegExp('^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$')
      if (minVal && +val <= +minVal) {
        callBack(new Error(`数据应大于最小值:${minVal}`))
      } else if (!val) {
        callBack(new Error('请输入正确的金额!'))
      } else if (reg.test(val) === false) {
        callBack(new Error('请输入最多包含2位小数的正数!'))
      } else {
        callBack()
      }
    },
    // 校验可兑换范围的最小值
    handleLimitMin (rule, val, callBack, maxVal) {
      const reg = new RegExp('^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$')
      if (maxVal && +val >= +maxVal) {
        callBack(new Error(`数据应小于最大值:${maxVal}`))
      } else if (!val) {
        callBack(new Error('请输入正确的金额!'))
      } else if (reg.test(val) === false) {
        callBack(new Error('请输入最多包含2位小数的正数!'))
      } else {
        callBack()
      }
    },
    handleSetRuleType (val, row, index) {
      if (val === '3') {
        this.isShowSetPriceTable = true
      } else {
        this.isShowSetPriceTable = false
      }
    },
    validate () {
      console.log(this.$refs.CinemaRadio.validate(), 'this.$refs.CinemaRadio.validate()')
      return new Promise((resolve, reject) => {
        const arr = [this.$refs.form.validate(), this.$refs.CinemaRadio.validate()]
        Promise.all(arr).then(() => {
          resolve()
        }).catch(() => {
          reject('基础规则')
        })
      })
    },
    handleClearValue () {
      this.$set(this.innerItem, 'fixedPrice', '')
      this.$set(this.innerItem, 'increasePrice', '')
    }
  }
}
</script>

<style scoped lang='scss'>
</style>
